

class RequestmapEditorController {

    def index = {  redirect(action: "edit", params: params)}

    def edit = {  

        def maps = Requestmap.list(sort: 'url')
        def requestmaps = new TreeMap( [
            compare : { Object o1, Object o2 -> 
                o1 = (String)o1
                o2 = (String)o2
                return o1.compareTo(o2)
                }
            ] as Comparator)
        def content = new StringBuffer()
        
        grailsApplication.controllerClasses.each{ c ->
            def prefix = "/${c.logicalPropertyName}/**"
            def exist = maps.find { it?.url == prefix}
         
            if (exist) { 
                requestmaps.put(exist.url , exist.configAttribute)
                maps.remove(exist)
            }else{ 
                requestmaps.put(prefix , "")
            }                 
        }

        maps.each{
                requestmaps.put(it.url , it.configAttribute)
        }

        requestmaps.each {   key , value ->
                content.append(key)
                content.append('=')
                content.append(value)
                content.append('\n')  
        }
 
        [content : content.toString()]
    }

    def update = {
        def maps = params.content.split(/\r\n/)
        def map = new HashMap()
  
        maps.each{
            if (it && it.length() > 0 && it.indexOf('=') > 0) {
                def temp = it.split('=')
                if (temp.size()>1 ) {
//                    println temp[1]
                    map.put(temp[0], temp[1]) 
                }
            }
        }

        map.each{k , v ->
            def requestmap = Requestmap.findByUrl(k)
            requestmap = requestmap?requestmap : new Requestmap(url : k)
            requestmap.configAttribute = v
            requestmap.save()
        }
        redirect(action: "edit")
    }
}
